<?php
/**
 * 文章挂件
 * @author liuyemin
 *
 */
class ArticleWidget extends CWidget{
	
	public $cid = 0;	//查询文章的栏目ID号
	public $row = 5;	//需要显示多少条
	public $attrId;	//文章属性ID 
	public $label = '<li>';	//外层标记
	public $endLabel = '</li>';
	public $order;	//排序规则
	public $where;	//查询条件
	public $click;
	
	/**
	 * 挂件初始化
	 * @see CWidget::init()
	 */
	public function init(){
		
		//增加查询条件
		if(isset($this->cid) && $this->cid > 0){
			$this->where = "{{article}}.category_id = {$this->cid}";
		}
		
		//排序规则
		empty($this->order) && $this->order = '{{article}}.post_time DESC';
	}
	
	/**
	 * (non-PHPdoc)
	 * @see CWidget::run()
	 */
	public function run(){
		if(isset($this->label)){
			$this->endLabel = str_replace('<', '</', $this->label);
		}
		if(isset($this->attrId) && $this->attrId > 0){
			$this->getAttrArticle();
		} else {
			$this->getArticle();
		}
	}
	
	/**
	 * 获取包含属性的文章
	 */
	protected function getAttrArticle(){
		$this->where .= "{{article_attr}}.attr_id = {$this->attrId}";

		$list = Yii::app()->db->createCommand()
				->select('{{article}}.title, {{article}}.article_id')
				->from('{{article_attr}}')
				->leftJoin('{{article}}', '{{article_attr}}.article_id = {{article}}.article_id')
				->where($this->where)
				->order($this->order)
				->limit($this->row)
				->queryAll();
		foreach($list as $v){
			echo $this->label.'<a href="'.Yii::app()->controller->createUrl('detail/index',array('article_id'=>$v['article_id'])).'">'.$v['title'].'</a>'.$this->endLabel;
		}
	}
	
	/**
	 * 获取一般文章
	 */
	protected function getArticle(){
		$list = Yii::app()->db->createCommand()
				->select('article_id,title')
				->from('{{article}}')
				->where($this->where)
				->limit($this->row)
				->order($this->order)
				->queryAll();
		foreach($list as $v){
			echo $this->label.'<a href="'.Yii::app()->controller->createUrl('detail/index',array('article_id'=>$v['article_id'])).'">'.$v['title'].'</a>'.$this->endLabel;
		}
	}
}